<template>
    <el-header>
        <el-text size="large" tag="b">采购申请</el-text>
        <el-tabs v-model="activeName" class="custom-tabs" @tab-click="handleClick">
            <el-tab-pane label="申请列表" name="applyList">
                <div style="float: left; margin-bottom: 16px;">
                    <el-form :model="form" label-width="auto" style="display: flex; gap: 24px;">
                        <el-input v-model="form.searchInput" style="width: 200px; height: 2rem;"
                            placeholder="按申请编号，申请人" />
                        <el-form-item label="日期：" prop="valid_period">
                            <el-date-picker v-model="form.dateRange" type="datetimerange" range-separator="~"
                                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;" />
                        </el-form-item>
                        <el-form-item label="审核状态：">
                            <el-select v-model="form.auditStatus" placeholder="请选择审核状态" clearable style="width: 120px;">
                                <el-option label="全部" value="" />
                                <el-option label="已审核" value="已审核" />
                                <el-option label="审核中" value="审核中" />
                                <el-option label="未通过" value="未通过" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="申请状态：">
                            <el-select v-model="form.applySatus" placeholder="请选择审核状态" clearable style="width: 120px;">
                                <el-option label="全部" value="" />
                                <el-option label="待分单" value="待分单" />
                                <el-option label="待审核" value="待审核" />
                                <el-option label="已完成" value="已完成" />
                                <el-option label="已驳回" value="已驳回" />
                            </el-select>
                        </el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>

                    </el-form>
                </div>
                <div style="gap: 12px; float: right; margin-bottom: 16px;">
                    <el-button type="primary" @click="showAddApply">新增</el-button>
                    <el-button>导入</el-button>
                    <el-button>导出</el-button>
                </div>
                <div class="table-wrapper">
                    <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName"
                        v-if="activeName === 'applyList'" height="100%">
                        <el-table-column type="selection" width="55px">
                        </el-table-column>
                        <el-table-column label="操作" width="180" fixed="right">
                            <template #default="scope">
                                <el-button size="small" type="danger">删除</el-button>
                                <el-button size="small" type="primary" v-if="scope.row.processStatus === '待审核'"  @click="modifyApply(scope.row)">编辑</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyCode" label="申请编号" width="180" />
                        <el-table-column prop="applicant" label="申请人" width="180" />
                        <el-table-column prop="department" label="申请部门" width="180" />
                        <el-table-column label="申请明细" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="deplayApplyGoods(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="auditStatus" label="审核状态" width="180">
                            <template #default="scope">
                                <el-tag :type="getStatusTagType(scope.row.auditStatus)">
                                    {{ scope.row.auditStatus }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核记录" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="viewAuditRecord(scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyReason" label="申请原因" width="180" />
                        <el-table-column prop="processStatus" label="处理状态" width="180">
                            <template #default="scope">
                                <el-tag :type="getProcessTagType(scope.row.processStatus)">
                                    {{ scope.row.processStatus }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyDate" label="申请日期" width="180" />
                        <el-table-column prop="applyDate" label="报价截止日期" width="180" />
                    </el-table>
                </div>
                <el-pagination style="float: right; margin-top: 16px;" background layout="prev, pager, next,jumper"
                    :total="pageInfo.total" :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum"
                    @current-change="changePage" />
            </el-tab-pane>
            <el-tab-pane label="待审核申请" name="pendingReview">
                <div style="float: left; margin-bottom: 16px;">
                    <el-form :model="form" label-width="auto" style="display: flex; gap: 24px;">
                        <el-input v-model="form.searchInput" style="width: 200px; height: 2rem;"
                            placeholder="按申请编号，申请人" />
                        <el-form-item label="日期：" prop="valid_period">
                            <el-date-picker v-model="form.dateRange" type="datetimerange" range-separator="~"
                                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;" />
                        </el-form-item>
                        <el-form-item label="审核状态：">
                            <el-select v-model="form.auditStatus" placeholder="请选择审核状态" clearable style="width: 120px;">
                                <el-option label="全部" value="" />
                                <el-option label="已审核" value="已审核" />
                                <el-option label="审核中" value="审核中" />
                                <el-option label="未通过" value="未通过" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="申请状态：">
                            <el-select v-model="form.applySatus" placeholder="请选择审核状态" clearable style="width: 120px;">
                                <el-option label="全部" value="" />
                                <el-option label="待分单" value="待分单" />
                                <el-option label="待审核" value="待审核" />
                                <el-option label="已完成" value="已完成" />
                                <el-option label="已驳回" value="已驳回" />
                            </el-select>
                        </el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>

                    </el-form>
                </div>
                <div style="gap: 12px; float: right; margin-bottom: 16px;">
                    <el-button type="primary" @click="showAddApply">新增</el-button>
                    <el-button>导入</el-button>
                    <el-button>导出</el-button>
                </div>
                <div class="table-wrapper">
                    <el-table :data="pendingReviewData" style="width: 100%" :row-class-name="tableRowClassName"
                        v-if="activeName === 'pendingReview'" height="100%">
                        <el-table-column type="selection" width="55px">
                        </el-table-column>
                        <el-table-column label="操作" width="180" fixed="right">
                            <template #default="scope">
                                <el-button size="small" type="warning" @click="checkApply(scope.row)">审核</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyCode" label="申请编号" width="180" />
                        <el-table-column prop="applicant" label="申请人" width="180" />
                        <el-table-column prop="department" label="申请部门" width="180" />
                        <el-table-column label="申请明细" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="deplayApplyGoods(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="auditStatus" label="审核状态" width="180">
                            <template #default="scope">
                                <el-tag type="warning">{{ scope.row.auditStatus }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核记录" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="viewAuditRecord(scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyReason" label="申请原因" width="180" />
                        <el-table-column prop="processStatus" label="处理状态" width="180">
                            <template #default="scope">
                                <el-tag>{{ scope.row.processStatus }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyDate" label="申请日期" width="180" />
                    </el-table>
                </div>
                <el-pagination style="float: right; margin-top: 16px;" background layout="prev, pager, next,jumper"
                    :total="pageInfo.total" :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum"
                    @current-change="changePage" />
            </el-tab-pane>
            <el-tab-pane label="待分单" name="pendingAllocation">
                <div style="float: left; margin-bottom: 16px;">
                    <el-form :model="form" label-width="auto" style="display: flex; gap: 24px;">
                        <el-input v-model="form.searchInput" style="width: 200px; height: 2rem;"
                            placeholder="按申请编号，申请人" />
                        <el-form-item label="日期：" prop="valid_period">
                            <el-date-picker v-model="form.dateRange" type="datetimerange" range-separator="~"
                                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;" />
                        </el-form-item>
                        <el-form-item label="审核状态：">
                            <el-select v-model="form.auditStatus" placeholder="请选择审核状态" clearable style="width: 120px;">
                                <el-option label="全部" value="" />
                                <el-option label="已审核" value="已审核" />
                                <el-option label="审核中" value="审核中" />
                                <el-option label="未通过" value="未通过" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="申请状态：">
                            <el-select v-model="form.applySatus" placeholder="请选择审核状态" clearable style="width: 120px;">
                                <el-option label="全部" value="" />
                                <el-option label="待分单" value="待分单" />
                                <el-option label="待审核" value="待审核" />
                                <el-option label="已完成" value="已完成" />
                                <el-option label="已驳回" value="已驳回" />
                            </el-select>
                        </el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>

                    </el-form>
                </div>
                <div style="gap: 12px; float: right; margin-bottom: 16px;">
                    <el-button type="primary" @click="showAddApply">新增</el-button>
                    <el-button>导入</el-button>
                    <el-button>导出</el-button>
                </div>
                <div class="table-wrapper">
                    <el-table :data="pendingAllocationData" style="width: 100%" :row-class-name="tableRowClassName"
                        v-if="activeName === 'pendingAllocation'" height="100%">
                        <el-table-column type="selection" width="55px">
                        </el-table-column>
                        <el-table-column label="操作" width="180" fixed="right">
                            <template #default="scope">
                                <el-button size="small" type="warning" @click="splitOrder(scope.row)">分单</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyCode" label="申请编号" width="180" />
                        <el-table-column prop="applicant" label="申请人" width="180" />
                        <el-table-column prop="department" label="申请部门" width="180" />
                        <el-table-column label="申请明细" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="deplayApplyGoods(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="auditStatus" label="审核状态" width="180">
                            <template #default="scope">
                                <el-tag type="success">{{ scope.row.auditStatus }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核记录" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="viewAuditRecord(scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyReason" label="申请原因" width="180" />
                        <el-table-column prop="processStatus" label="处理状态" width="180">
                            <template #default="scope">
                                <el-tag type="info">{{ scope.row.processStatus }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="applyDate" label="申请日期" width="180" />
                    </el-table>
                </div>
                <el-pagination style="float: right; margin-top: 16px;" background layout="prev, pager, next,jumper"
                    :total="pageInfo.total" :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum"
                    @current-change="changePage" />
            </el-tab-pane>
        </el-tabs>

        <!-- 对话框部分保持不变 -->
        <el-dialog v-model="showAddApplyView" title="新增采购申请">
            <el-form>
                <AddProcurementApply></AddProcurementApply>
            </el-form>
        </el-dialog>

        <el-dialog v-model="modifyApplyView" title="" class="fixed-height-dialog" width="60%">
            <div class="purchase-apply-container">
                <el-card class="form-card">
                    <template #header>
                        <div class="card-header">
                            <span class="form-title">修改采购申请</span>
                        </div>
                    </template>

                    <el-form :model="modifyForm" label-width="100px" class="purchase-form">
                        <!-- 基本信息 -->
                        <div class="form-section">
                            <div class="section-title">基本信息</div>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="申请人">
                                        <el-input v-model="modifyForm.applicant" placeholder="请输入申请人" clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="申请部门">
                                        <el-input v-model="modifyForm.department" placeholder="请输入申请部门" clearable />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <!-- 申请原因 -->
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="申请原因">
                                        <el-input v-model="modifyForm.applyReason" type="textarea" :rows="3"
                                            placeholder="请输入申请原因" maxlength="500" show-word-limit />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>

                        <!-- 申请明细 -->
                        <div class="form-section">
                            <div class="section-title">
                                申请明细
                                <el-button type="primary" link @click="openGoodsDialog" style="margin-left: 10px;">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>添加物品
                                </el-button>
                            </div>

                            <el-table :data="currentApplyGoodsDetails" height="200" style="width: 100%;">
                                <el-table-column label="序号" type="index" width="60" />
                                <el-table-column property="goodsName" label="产品名称" width="180" />
                                <el-table-column property="applyQuantity" label="采购数量" width="120" />
                                <el-table-column property="applyCode" label="采购编号" width="180" />
                                <el-table-column property="goodsType" label="产品类别" width="120" />
                                <el-table-column property="goodsBrand" label="产品品牌" width="120" />
                                <el-table-column property="goodsMeasure" label="计量单位" width="100" />
                                <el-table-column label="图片" width="120">
                                    <template #default="scope">
                                        <span v-if="!scope.row.goodsPhoto">无图片</span>
                                        <img v-else :src="scope.row.goodsPhoto"
                                            style="width: 40px; height: 40px; object-fit: cover;" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="80" align="center">
                                    <template #default="{ $index }">
                                        <el-button type="danger" link @click="removeItem($index)">
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination :page-size="20" :pager-count="11" layout="prev, pager, next, jumper"
                                :total="1000" size="small" />
                        </div>

                        <!-- 表单操作按钮 -->
                        <div class="form-actions">
                            <el-button type="primary" @click="handleSubmit">提交修改</el-button>
                            <el-button @click="handleReset">重置</el-button>
                            <el-button @click="handleCancel">取消</el-button>
                        </div>
                    </el-form>
                </el-card>
            </div>
        </el-dialog>

        <!-- 商品选择对话框 -->
        <el-dialog v-model="openGoodsDialogView" title="选择商品" class="fixed-height-dialog" width="60%">
            <SelectGoods :visible="openGoodsDialogView" @update:visible="openGoodsDialogView = $event"
                @confirm="handleGoodsConfirm" />
        </el-dialog>

        <!-- 审核对话框 -->
        <el-dialog v-model="checkView" title="" class="fixed-height-dialog" width="60%">
            <div class="purchase-apply-container">
                <el-card class="form-card">
                    <template #header>
                        <div class="card-header">
                            <span class="form-title">采购申请审核</span>
                        </div>
                    </template>

                    <el-form :model="modifyForm" label-width="100px" class="purchase-form">
                        <!-- 审核信息 -->
                        <div class="form-section">
                            <el-radio-group v-model="radio1">
                                <el-radio value="1" size="large">通过</el-radio>
                                <el-radio value="2" size="large">拒绝</el-radio>
                            </el-radio-group>
                        </div>
                        <!-- 基本信息 -->
                        <div class="form-section">
                            <div class="section-title">基本信息</div>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="申请人">
                                        <el-input v-model="modifyForm.applicant" placeholder="请输入申请人" clearable
                                            disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="申请部门">
                                        <el-input v-model="modifyForm.department" placeholder="请输入申请部门" clearable
                                            disabled />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <!-- 申请原因 -->
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="申请原因">
                                        <el-input v-model="modifyForm.applyReason" type="textarea" :rows="3"
                                            placeholder="请输入申请原因" maxlength="500" show-word-limit />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>

                        <!-- 申请明细 -->
                        <div class="form-section">
                            <div class="section-title">
                                申请明细
                            </div>

                            <el-table :data="currentApplyGoodsDetails" height="200" style="width: 100%;">
                                <el-table-column label="序号" type="index" width="60" />
                                <el-table-column property="goodsName" label="产品名称" width="180" />
                                <el-table-column property="applyQuantity" label="采购数量" width="120" />
                                <el-table-column property="applyCode" label="采购编号" width="180" />
                                <el-table-column property="goodsType" label="产品类别" width="120" />
                                <el-table-column property="goodsBrand" label="产品品牌" width="120" />
                                <el-table-column property="goodsMeasure" label="计量单位" width="100" />
                                <el-table-column label="图片" width="120">
                                    <template #default="scope">
                                        <span v-if="!scope.row.goodsPhoto">无图片</span>
                                        <img v-else :src="scope.row.goodsPhoto"
                                            style="width: 40px; height: 40px; object-fit: cover;" />
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination :page-size="20" :pager-count="11" layout="prev, pager, next, jumper"
                                :total="1000" size="small" />
                        </div>

                        <!-- 表单操作按钮 -->
                        <div class="form-actions">
                            <el-button type="primary" @click="handleAuditSubmit">提交</el-button>
                            <el-button @click="handleCancel">取消</el-button>
                        </div>
                    </el-form>
                </el-card>
            </div>
        </el-dialog>
        <el-dialog v-model="deplayApplyGoodsView" title="申请明细" class="fixed-height-dialog" width="60%">
            <el-form style="display: flex; gap: 16px;">
                <el-form-item>
                    <el-input placeholder="" style="width: 250px;"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="currentApplyGoodsDetails" height="200" style="width: 100%;">
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column property="goodsName" label="产品名称" width="180" />
                <el-table-column property="applyQuantity" label="采购数量" width="120" />
                <el-table-column property="applyCode" label="采购编号" width="180" />
                <el-table-column property="goodsType" label="产品类别" width="120" />
                <el-table-column property="goodsBrand" label="产品品牌" width="120" />
                <el-table-column property="goodsMeasure" label="计量单位" width="100" />
                <el-table-column label="图片" width="120">
                    <template #default="scope">
                        <span v-if="!scope.row.goodsPhoto">无图片</span>
                        <img v-else :src="scope.row.goodsPhoto" style="width: 40px; height: 40px; object-fit: cover;" />
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :page-size="20" :pager-count="11" layout="prev, pager, next, jumper" :total="1000"
                size="small" />
        </el-dialog>

        <!-- 分单 -->
        <el-dialog v-model="splitOrderView" title="" class="fixed-height-dialog" width="60%">
            <div class="purchase-apply-container">
                <el-card class="form-card">
                    <template #header>
                        <div class="card-header">
                            <span class="form-title">采购分单</span>
                        </div>
                    </template>

                    <el-form label-width="100px" class="purchase-form">
                        <!-- 分单明细 -->
                        <div class="form-section">
                            <div class="section-title">
                                分单明细
                            </div>

                            <el-table :data="currentApplyGoodsDetails" height="200" style="width: 100%;">
                                <el-table-column label="序号" type="index" width="60" />
                                <el-table-column property="goodsName" label="产品名称" width="180">
                                </el-table-column>
                                <el-table-column property="applyQuantity" label="采购数量" width="120">
                                </el-table-column>
                                <el-table-column property="supplierName" label="供应商" width="180">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.supplierName" placeholder="供应商"
                                            @click="openSupplierDialogForItem(scope.row)" readonly />
                                    </template>
                                </el-table-column>
                                <el-table-column property="buyPrice" label="采购单价" width="120">
                                    <template #default="scope">
                                        <el-input-number v-model="scope.row.buyPrice" :min="0" :precision="2"
                                            controls-position="right" style="width: 100%"
                                            @change="calculateItemTotal(scope.row)" />
                                    </template>
                                </el-table-column>
                                <el-table-column property="buyTotalPrice" label="采购小计" width="120">
                                    <template #default="scope">
                                        <span>¥{{ scope.row.buyTotalPrice?.toFixed(2) || '0.00' }}</span>
                                    </template>
                                </el-table-column>

                                <el-table-column label="操作" width="80" align="center">
                                    <template #default="{ $index }">
                                        <el-button type="danger" link @click="removeOrderItem($index)">
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>

                        <!-- 表单操作按钮 -->
                        <div class="form-actions">
                            <el-button type="primary" @click="handleModifySubmit">提交修改</el-button>
                            <el-button @click="handleModifyReset">重置</el-button>
                            <el-button @click="handleModifyCancel">取消</el-button>
                        </div>
                    </el-form>
                </el-card>
            </div>
        </el-dialog>

        <!-- 供应商选择对话框 -->
        <el-dialog v-model="showSupplierDialog" title="供应商比价" width="70%">
            <div class="supplier-dialog">
                <!-- 搜索区域 -->
                <el-form :model="supplierSearchForm" label-width="auto" style="margin-bottom: 16px;">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="商品名称">
                                <el-input v-model="supplierSearchForm.goodsName" placeholder="输入商品名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="供应商">
                                <el-input v-model="supplierSearchForm.supplierName" placeholder="输入供应商名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item>
                                <el-button type="primary" @click="searchSuppliers">查询</el-button>
                                <el-button @click="resetSupplierSearch">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 供应商比价表格 -->
                <el-table :data="supplierList" height="400" style="width: 100%;" @row-click="selectSupplier">
                    <el-table-column label="选择" width="60" align="center">
                        <template #default="scope">
                            <el-radio v-model="selectedSupplier" :label="scope.row">{{ '' }}</el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column prop="supplierName" label="供应商名称" width="180" />
                    <el-table-column prop="goodsName" label="商品名称" width="180" />
                    <el-table-column prop="avgPrice" label="采购均价" width="120">
                        <template #default="scope">
                            ¥{{ scope.row.avgPrice?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="minPrice" label="采购低价" width="120">
                        <template #default="scope">
                            ¥{{ scope.row.minPrice?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="recentPrice" label="推荐价格" width="120">
                        <template #default="scope">
                            <span style="color: #409EFF; font-weight: bold;">
                                ¥{{ scope.row.recentPrice?.toFixed(2) || '0.00' }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recentTransaction" label="最近交易时间" width="150" />
                    <el-table-column prop="contactPerson" label="联系人" width="120" />
                    <el-table-column prop="contactPhone" label="联系电话" width="130" />
                </el-table>

                <!-- 分页 -->
                <el-pagination style="margin-top: 16px;" background layout="prev, pager, next, jumper"
                    :total="supplierTotal" :page-size="supplierPageInfo.pageSize"
                    :current-page="supplierPageInfo.pageNum" @current-change="changeSupplierPage" />

                <!-- 对话框操作按钮 -->
                <div class="dialog-footer" style="margin-top: 16px; text-align: center;">
                    <el-button type="primary" @click="confirmSupplier">确定选择</el-button>
                    <el-button @click="cancelSupplier">取消</el-button>
                </div>
            </div>
        </el-dialog>
    </el-header>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { ElMessage } from 'element-plus';
// import AddProcurementApply from './AddProcurementApply.vue';
import SelectGoods from './SelectGoods.vue'; // 这个导入现在被使用了
import AddProcurementApply from './AddProcurement.vue';

const radio1 = ref('1')
const activeName = ref('applyList');
const form = ref({
    searchInput: '',
    auditStatus: '',
    applySatus: ''
})

// 对话框状态
const showAddApplyView = ref(false)
const deplayApplyGoodsView = ref(false)
const modifyApplyView = ref(false)
const checkView = ref(false)
const openGoodsDialogView = ref(false)
const splitOrderView = ref(false)
const showSupplierDialog = ref(false)

// 当前数据
const currentApplyGoodsDetails = ref([])
// 当前编辑的商品项
const currentEditItem = ref(null)

// 修改表单数据 - 使用 reactive 创建响应式对象
const modifyForm = reactive({
    id: '',
    applyCode: '',
    applicant: '',
    department: '',
    applyReason: '',
    auditStatus: '',
    processStatus: '',
    applyDate: ''
})

// 优化后的表格数据
const tableData = ref([
    {
        id: 1,
        applyCode: 'SQ202401001',
        applicant: '张三',
        department: '采购部',
        applyReason: '日常办公用品采购',
        auditStatus: '已审核',
        processStatus: '待分单',
        applyDate: '2024-01-15',
        applyGoodsDetails: [
            {
                goodsName: 'A4打印纸',
                applyQuantity: 100,
                applyCode: 'CG202401001',
                goodsType: '办公用品',
                goodsBrand: '晨光',
                goodsMeasure: '包',
                goodsPhoto: ''
            },
            {
                goodsName: '中性笔',
                applyQuantity: 50,
                applyCode: 'CG202401002',
                goodsType: '办公用品',
                goodsBrand: '真彩',
                goodsMeasure: '盒',
                goodsPhoto: ''
            }
        ]
    },
    {
        id: 2,
        applyCode: 'SQ202401002',
        applicant: '李四',
        department: '技术部',
        applyReason: '开发设备采购',
        auditStatus: '审核中',
        processStatus: '待审核',
        applyDate: '2024-01-16',
        applyGoodsDetails: [
            {
                goodsName: '笔记本电脑',
                applyQuantity: 5,
                applyCode: 'CG202401003',
                goodsType: '电子产品',
                goodsBrand: '联想',
                goodsMeasure: '台',
                goodsPhoto: ''
            }
        ]
    },
    {
        id: 3,
        applyCode: 'SQ202401003',
        applicant: '王五',
        department: '行政部',
        applyReason: '会议室设备更新',
        auditStatus: '未通过',
        processStatus: '已驳回',
        applyDate: '2024-01-17',
        applyGoodsDetails: [
            {
                goodsName: '投影仪',
                applyQuantity: 2,
                applyCode: 'CG202401004',
                goodsType: '电子产品',
                goodsBrand: '爱普生',
                goodsMeasure: '台',
                goodsPhoto: ''
            }
        ]
    },
    {
        id: 4,
        applyCode: 'SQ202401004',
        applicant: '赵六',
        department: '财务部',
        applyReason: '财务软件采购',
        auditStatus: '已审核',
        processStatus: '已完成',
        applyDate: '2024-01-18',
        applyGoodsDetails: [
            {
                goodsName: '财务软件',
                applyQuantity: 1,
                applyCode: 'CG202401005',
                goodsType: '软件',
                goodsBrand: '用友',
                goodsMeasure: '套',
                goodsPhoto: ''
            }
        ]
    }
]);

// 计算属性：根据状态筛选数据
const pendingReviewData = computed(() =>
    tableData.value.filter(item => item.auditStatus === '审核中')
);

const pendingAllocationData = computed(() =>
    tableData.value.filter(item => item.processStatus === '待分单')
);

const pageInfo = ref({
    total: 10,
    pageSize: 5,
    pageNum: 1
});

// 方法
const showAddApply = () => {
    showAddApplyView.value = true
}

const deplayApplyGoods = (row) => {
    deplayApplyGoodsView.value = true
    currentApplyGoodsDetails.value = row.applyGoodsDetails || []
}

const modifyApply = (row) => {
    modifyApplyView.value = true
    // 将行数据赋值给表单对象
    Object.assign(modifyForm, row)
    currentApplyGoodsDetails.value = row.applyGoodsDetails || []
}

const checkApply = (row) => {
    checkView.value = true
    // 将行数据赋值给表单对象
    Object.assign(modifyForm, row)
    currentApplyGoodsDetails.value = row.applyGoodsDetails || []
}
const splitOrder = (row) => {
    splitOrderView.value = true
    Object.assign(modifyForm, row)
    currentApplyGoodsDetails.value = row.applyGoodsDetails
}
const openGoodsDialog = () => {
    openGoodsDialogView.value = true
}


// 这个函数现在被使用了
const handleGoodsConfirm = (selectedGoods) => {
    console.log('选中的商品:', selectedGoods)
    // 添加选中的商品到申请明细
    if (selectedGoods && selectedGoods.length > 0) {
        // 如果是单个商品，转换为数组
        const goodsToAdd = Array.isArray(selectedGoods) ? selectedGoods : [selectedGoods]
        currentApplyGoodsDetails.value.push(...goodsToAdd)
        ElMessage.success(`成功添加 ${goodsToAdd.length} 个商品`)
    }
    openGoodsDialogView.value = false
}

const removeItem = (index) => {
    currentApplyGoodsDetails.value.splice(index, 1)
    ElMessage.success('删除成功')
}

const handleSubmit = () => {
    console.log('提交修改的数据:', {
        ...modifyForm,
        applyGoodsDetails: currentApplyGoodsDetails.value
    })
    ElMessage.success('修改成功')
    modifyApplyView.value = false
}

const handleAuditSubmit = () => {
    console.log('审核提交:', {
        ...modifyForm,
        auditResult: radio1.value,
        applyGoodsDetails: currentApplyGoodsDetails.value
    })
    ElMessage.success('审核提交成功')
    checkView.value = false
}

const handleReset = () => {
    // 重置表单，但保留当前编辑的数据
    ElMessage.info('表单已重置')
}

const handleCancel = () => {
    modifyApplyView.value = false
    checkView.value = false
    // 清空表单数据
    Object.keys(modifyForm).forEach(key => {
        modifyForm[key] = ''
    })
    currentApplyGoodsDetails.value = []
}

const viewAuditRecord = (row) => {
    console.log('查看审核记录:', row)
    ElMessage.info('查看审核记录功能开发中...')
}

// 状态标签类型
const getStatusTagType = (status) => {
    const statusMap = {
        '已审核': 'success',
        '审核中': 'warning',
        '未通过': 'danger'
    }
    return statusMap[status] || 'info'
}

const getProcessTagType = (status) => {
    const statusMap = {
        '待分单': 'warning',
        '待审核': 'info',
        '已驳回': 'danger',
        '已完成': 'success'
    }
    return statusMap[status] || 'info'
}

const handleClick = (tab) => {
    console.log('切换到标签:', tab.paneName);
};

const changePage = (page) => {
    pageInfo.value.pageNum = page;
};

const tableRowClassName = ({ rowIndex }) => {
    return {
        'table-row-even': rowIndex % 2 === 0,
        'table-row-odd': rowIndex % 2 !== 0
    };
};

const onSubmit = () => {
    console.log('查询参数：', form);
    ElMessage.info('查询功能开发中...')
};

//分单
// 供应商相关数据
const supplierSearchForm = reactive({
    goodsName: '',
    supplierName: ''
})

const supplierList = ref([
    {
        supplierName: '供应商A',
        goodsName: '商品A',
        avgPrice: 100,
        minPrice: 95,
        recentPrice: 98,
        recentTransaction: '2024-01-15',
        contactPerson: '张三',
        contactPhone: '13800138000'
    },
    {
        supplierName: '供应商B',
        goodsName: '商品A',
        avgPrice: 102,
        minPrice: 98,
        recentPrice: 100,
        recentTransaction: '2024-01-10',
        contactPerson: '李四',
        contactPhone: '13900139000'
    }
])

const selectedSupplier = ref(null)
const supplierPageInfo = reactive({
    pageNum: 1,
    pageSize: 10
})
const supplierTotal = ref(2)

// 打开供应商对话框
const openSupplierDialogForItem = (item) => {
    currentEditItem.value = item
    showSupplierDialog.value = true
    // 根据当前商品搜索供应商
    supplierSearchForm.goodsName = item.goodsName
    searchSuppliers()
}

// 选择供应商
const selectSupplier = (row) => {
    selectedSupplier.value = row
}

// 确认选择供应商
const confirmSupplier = () => {
    if (selectedSupplier.value && currentEditItem.value) {
        // 更新商品项的供应商信息和价格
        currentEditItem.value.supplierName = selectedSupplier.value.supplierName
        currentEditItem.value.buyPrice = selectedSupplier.value.recentPrice || selectedSupplier.value.avgPrice

        // 计算采购小计
        calculateItemTotal(currentEditItem.value)

        showSupplierDialog.value = false
        selectedSupplier.value = null
        currentEditItem.value = null
    } else {
        ElMessage.warning('请选择一个供应商')
    }
}

// 取消选择供应商
const cancelSupplier = () => {
    showSupplierDialog.value = false
    selectedSupplier.value = null
    currentEditItem.value = null
}

// 计算单个商品项的小计
const calculateItemTotal = (item) => {
    if (item.applyQuantity && item.buyPrice) {
        item.buyTotalPrice = item.applyQuantity * item.buyPrice
    } else {
        item.buyTotalPrice = 0
    }
}

// // 计算总金额
// const totalAmount = computed(() => {
//     return currentApplyGoodsDetails.value.reduce((total, item) => {
//         return total + (item.buyTotalPrice || 0)
//     }, 0)
// })

// 搜索供应商
const searchSuppliers = () => {
    // 模拟搜索逻辑
    console.log('搜索供应商:', supplierSearchForm)
    // 这里应该调用API获取供应商列表
}

// 重置供应商搜索
const resetSupplierSearch = () => {
    supplierSearchForm.goodsName = ''
    supplierSearchForm.supplierName = ''
    searchSuppliers()
}

// 分页变化
const changeSupplierPage = (page) => {
    supplierPageInfo.pageNum = page
    searchSuppliers()
}

// 删除商品项
const removeOrderItem = (index) => {
    currentApplyGoodsDetails.value.splice(index, 1)
}

// 提交修改
const handleModifySubmit = () => {
    console.log('提交分单数据:', currentApplyGoodsDetails.value)
    ElMessage.success('分单提交成功')
    splitOrderView.value = false
}

// 重置表单
const handleModifyReset = () => {
    currentApplyGoodsDetails.value.forEach(item => {
        item.supplierName = ''
        item.buyPrice = 0
        item.buyTotalPrice = 0
    })
}

// 取消操作
const handleModifyCancel = () => {
    splitOrderView.value = false
}
</script>

<style scoped>
/* 固定高度对话框样式 */
.fixed-height-dialog {
    max-height: 80vh;
}

:deep(.fixed-height-dialog .el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;
}

.dialog-content {
    min-height: 400px;
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

/* 核心修改：表格容器样式 */
.table-wrapper {
    height: 400px;
    /* 固定高度，这是关键 */
    overflow: auto;
    border: 1px solid #e8e8e8;
    display: block;
    clear: both;
}

/* 确保表头固定 */
:deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
}

/* 可选：给表头添加背景色，避免透明 */
:deep(.el-table th) {
    background-color: #f5f7fa;
}

/* 隔行变色样式 */
:deep(.table-row-even) {
    background-color: #f9f9f9;
}

:deep(.table-row-odd) {
    background-color: #fff;
}

/* 样式与基础版相同，增加以下样式 */
.form-section {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

.items-table {
    margin-bottom: 16px;
}

.total-amount {
    text-align: right;
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
}

.amount {
    font-size: 18px;
    color: #e6a23c;
}
</style>